
package br.unirio.bsi.dsw.AuctionSite.action;

import flexjson.JSONSerializer;

import org.apache.struts.action.*;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.unirio.bsi.dsw.AuctionSite.beans.loginForm;
import br.unirio.bsi.dsw.AuctionSite.model.dao.GenericDAO;

import br.unirio.bsi.dsw.AuctionSite.beans.formBeanC;
import br.unirio.bsi.dsw.AuctionSite.beans.commentForm;
import java.sql.Date;
import java.sql.Timestamp;

public class commentAction extends Action 
{
  @Override
  public ActionForward execute(ActionMapping mapping, 
                               ActionForm form,
                               HttpServletRequest request, 
                               HttpServletResponse response) throws Exception 
  {      
    // pega a session
    HttpSession session = request.getSession();  
    
    // check logged
    loginForm lf = (loginForm)session.getAttribute("loginForm"); 
    if( lf == null || !lf.isLogged() )
      return null;
    
    // pega instancia do DAO    
    GenericDAO gD = GenericDAO.getInstance(getResources(request).getMessage("DB_NAME"));
    
    // copy
    commentForm cF = (commentForm)form;
    
    // parameter
    if( cF.getOperation() != null && 
        cF.getOperation().equals( commentForm.OPERATION_INSERT ) )
    {
      String selAlb = cF.getSelectedAlbum();
      if( selAlb != null && !selAlb.isEmpty() )
      {      
        // alloca novo comment
        formBeanC comment = new formBeanC();  
        
        comment.setIDCommentUsuario(0);
        comment.setIDCommentAlbum( Integer.parseInt( selAlb ) );
        comment.setIDUsuario(lf.getId());
        comment.setData( new Timestamp( new java.util.Date().getTime() ) );
        comment.setTexto( cF.getComment() );

        // coloca no banco
        gD.insert( comment );
      }
    }
    else
    if( cF.getOperation() != null && 
        cF.getOperation().equals( commentForm.OPERATION_DELETE ) )
    {
      // alloca novo comment
      formBeanC comment = new formBeanC();      
      comment.setID( Integer.parseInt( cF.getSelectedComment() ) );
      
      gD.retrieve( comment );
      cF.setSelectedAlbum( comment.getIDCommentAlbum().toString() );
      
      // verifica se o comentario eh do usuario logado
      if( comment.getIDUsuario() == lf.getId() )
        // remove do banco
        gD.execute( "DELETE FROM Comentario WHERE ID=" + cF.getSelectedComment() );
    }      
    
    // return listing
    String selPage = cF.getSelectedPage();
    String selArt = cF.getSelectedArtista();
    String selEst = cF.getSelectedEstilo();
    String selAlb = cF.getSelectedAlbum();
    String search = cF.getSearch();
    
    if( selArt != null && !selArt.equals("") )
    {
      gD.retrieveAll( "SELECT DISTINCT c.*, a.nome as albumNome, u.nome as usuarioNome " +
                      "FROM Comentario c, Album a, Artista b, Usuario u " +
                      "WHERE  b.id = " + selArt +
                      " AND   c.idcommentalbum = a.id " +
                      " AND   b.id = a.idartista " +   
                      " AND   u.id = c.idusuario " +                 
                      " ORDER BY a.nome ASC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanC.class, cF.getComments() );      
    }
    else    
    if( selEst != null && !selEst.equals("") )
    {
      gD.retrieveAll( "SELECT DISTINCT c.*, a.nome as albumNome, u.nome as usuarioNome " +
                      "FROM Comentario c, Album a, Artista b, Usuario u, EstiloArtista ea " +
                      "WHERE  ea.idestilo = " + selEst +
                      " AND   ea.idartista = a.idartista " +
                      " AND   c.idcommentalbum = a.id " +
                      " AND   b.id = a.idartista " +   
                      " AND   u.id = c.idusuario " +                 
                      " ORDER BY a.nome ASC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanC.class, cF.getComments() );    
    }
    else
    if( selAlb != null && !selAlb.equals("") )
    {
      gD.retrieveAll( "SELECT DISTINCT c.*, a.nome as albumNome, u.nome as usuarioNome " +
                      "FROM Comentario c, Album a, Artista b, Usuario u " +
                      "WHERE  c.idcommentalbum = " + selAlb +
                      " AND   c.idcommentalbum = a.id " +
                      " AND   b.id = a.idartista " +   
                      " AND   u.id = c.idusuario " +                 
                      " ORDER BY a.nome ASC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanC.class, cF.getComments() );
    }    
    else
    if( search != null && !search.equals("") )
    {
      gD.retrieveAll( "SELECT DISTINCT c.*, a.nome as albumNome, u.nome as usuarioNome " +
                      "FROM Comentario c, Album a, Artista b, Usuario u, Musica m " +
                      "WHERE  c.idcommentalbum = m.idalbum" +
                      " AND   c.idcommentalbum = a.id " +
                      " AND   b.id = a.idartista " +   
                      " AND   u.id = c.idusuario " +                 
                      " AND (a.nome ~* '"+ search + "'  " +
                      "   OR b.nome ~* '"+ search + "'  " +
                      "   OR m.nome ~* '"+ search + "') " +             
                      " ORDER BY a.nome ASC " +               
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanC.class, cF.getComments() );
    }    
    
    
    // parameter                   
    String jsonComments = new JSONSerializer()
                            .exclude("class").exclude("IDArtista")
                            .serialize( cF.getComments() );
    
    jsonComments = "({\"comments\":" + jsonComments + "})";
        
    response.getWriter().write( jsonComments );
    response.getWriter().flush();
    
    return null;
  }
}
